package com.bash;

import com.bash.QuoteData;
import com.bash.QuoteDataAdapter;

import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import java.net.*;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.XMLReader;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Top100 extends ListActivity
{
	Vector<QuoteData> quoteListVector = new Vector<QuoteData>();
	SAXParser parser = null;
	XMLReader reader = null;
	XMLHandler handler = new XMLHandler();
	ArrayAdapter<QuoteData> adapter = null;

	Dialog dialog = null;

	class XMLHandler implements org.xml.sax.ContentHandler
	{
		QuoteData currentQuote;
		String tag;

		public void endDocument(){}
	 	public void endPrefixMapping(String prefix){}
	 	public void ignorableWhitespace(char[] ch, int start, int length){}
	 	public void processingInstruction(String s, String a){}
	 	public void setDocumentLocator(Locator l){}
	 	public void skippedEntity(String name){}
	 	public void startDocument(){}
	 	public void startPrefixMapping(String prefix, String s){}

		public void characters(char[] ch, int start, int length)
		{
			if(tag.equals("hash")) {
				currentQuote.hash = String.copyValueOf(ch, start, length);
			} else if(tag.equals("text")) {
				currentQuote.text.add(String.copyValueOf(ch, start, length));
			} else if(tag.equals("qid")) {
				currentQuote.qid = Integer.parseInt(String.copyValueOf(ch, start, length));
			} else if(tag.equals("rating")) {
				currentQuote.rating = Integer.parseInt(String.copyValueOf(ch, start, length));
			}
		}
		public void startElement(String uri, String localName, String qName, Attributes atts)
		{
			tag = localName;
			if(tag.equals("quote")) {
				currentQuote = new QuoteData();
			}
		}

		public void endElement(String uri, String localName, String qName)
		{
			if(localName.equals("quote")) {
				if(currentQuote != null) {
					quoteListVector.add(currentQuote);
				}
			}
		 }
	}

	public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);

        Log.v("onCreate()", "IN");

        try {
        	setContentView(R.layout.latest);

        	SAXParserFactory f = SAXParserFactory.newInstance();
        	parser = f.newSAXParser();
        	reader = parser.getXMLReader();
        	reader.setContentHandler(handler);

        	adapter = new QuoteDataAdapter(Top100.this, R.layout.row);
        	setListAdapter(adapter);

        } catch (Exception e) {
        	Log.e("StationPicker", "Parser FAIL!");
        }
    }

    protected void onListItemClick(ListView l, View v, int position, long id)
    {
    	QuoteData selectedQuote = quoteListVector.elementAt(position);
    	final int qid = selectedQuote.qid;
    	dialog = new Dialog(this);
    	
    	Log.v("onListItemClick()", selectedQuote.getQid().toString());
    	
    	dialog.setContentView(R.layout.vote);
    	dialog.setTitle("Vote for this quote...");

    	dialog.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener()
    	{
            public void onClick(View v)
            {
            	dialog.dismiss();
            }
        });
    	
    	dialog.findViewById(R.id.rox).setOnClickListener(new View.OnClickListener()
    	{
            public void onClick(View v)
            {
            	Thread t = new Thread() 
            	{
            		public void run()
            		{
            			try {
            				URL url = new URL("http://bash.org/?le=41e720c83bacbd81c7e36bdb20e71307&rox="+ qid);
            				url.openStream();
        		     	} catch (Exception e) {
        		    		Log.e("onListItemClick()", "Thread", e); 
        		    	}

        		     	runOnUiThread(new Runnable()
        		     	{
        		     		public void run()
        		     		{
        		     			try {
        		     				dialog.dismiss();
        		     			}catch (Exception e) {
        		     				Log.e("onListItemClick()", "UIThread Runnable", e);
        		     			}
        		     			getListView().invalidate();
        		     		}
        		     	});
            		}
            	};
            	t.start();
            }
        });
    	
    	dialog.findViewById(R.id.sox).setOnClickListener(new View.OnClickListener()
    	{
            public void onClick(View v)
            {
            	Thread t = new Thread() 
            	{
            		public void run()
            		{
            			try {
            				URL url = new URL("http://bash.org/?le=41e720c83bacbd81c7e36bdb20e71307&sox="+ qid);
            				url.openStream();
        		     	} catch (Exception e) {
        		    		Log.e("onListItemClick()", "Thread", e); 
        		    	}

        		     	runOnUiThread(new Runnable()
        		     	{
        		     		public void run()
        		     		{
        		     			try {
        		     				dialog.dismiss();
        		     			}catch (Exception e) {
        		     				Log.e("onListItemClick()", "UIThread Runnable", e);
        		     			}
        		     			getListView().invalidate();
        		     		}
        		     	});
            		}
            	};
            	t.start();
            }
        });
    	
    	dialog.findViewById(R.id.sux).setOnClickListener(new View.OnClickListener()
    	{
            public void onClick(View v)
            {
            	Thread t = new Thread() 
            	{
            		public void run()
            		{
            			try {
            				URL url = new URL("http://bash.org/?le=41e720c83bacbd81c7e36bdb20e71307&sux="+ qid);
            				url.openStream();
        		     	} catch (Exception e) {
        		    		Log.e("onListItemClick()", "Thread", e); 
        		    	}

        		     	runOnUiThread(new Runnable()
        		     	{
        		     		public void run()
        		     		{
        		     			try {
        		     				dialog.dismiss();
        		     			}catch (Exception e) {
        		     				Log.e("onListItemClick()", "UIThread Runnable", e);
        		     			}
        		     			getListView().invalidate();
        		     		}
        		     	});
            		}
            	};
            	t.start();
            }
        });

    	dialog.show();
    }
    
    public void onStart()
    {
    	super.onStart();
    	Log.v("onStart()", "IN");

    	Thread t = new Thread() 
    	{
    		public void run()
    		{
    			URL url = null;

    			try {
		    		url = new URL("http://www.youspluge.com/api/top100");
		    		
		         	reader.parse(new InputSource(url.openStream()));

		         	Runnable r = new Runnable()
		         	{
		         		QuoteData qd = null;

		         		public void run()
		         		{
		         			try {
		         				int count = quoteListVector.size();
			         			for(int i = 0; i < count; i++)
			         			{
			         				qd = quoteListVector.elementAt(i);
			         				adapter.add(qd);
			         			}

			         			TextView t = (TextView) findViewById(R.id.loadingStatus);
			         			t.setText("Latest Quotes");
		         			}catch (Exception e) {
		         				Log.e("onStart()", "Runnable", e);
		         			}
		         			getListView().invalidate();
		         		}
		         	};

			    	runOnUiThread(r);

		     	} catch (Exception e) {
		    		Log.e("onStart()", "Exception", e); 
		    	}
    		}
    	};
    	t.start();
    }
    
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
	        case R.id.top100:
	    		return true;
	    	case R.id.top50:
	    		startActivity(new Intent(Top100.this, Top50.class));
	    		return true;
	        case R.id.random:
	        	startActivity(new Intent(Top100.this, Random.class));
	        	return true;
	        case R.id.latest:
	        	startActivity(new Intent(Top100.this, Latest.class));
	            return true;
        }

        return false;
    }
}